#include "RoleParser.h"

#include "RoleFunctionParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

RoleParser::RoleParser(
    QStringParser *&_idParser
    , RoleFunctionParser *&_roleFunctionParser
    , QStringParser *&_descriptionParser
    , QStringParser *&_publicKeyParser
    , QStringParser *&_authorityParser
):    m_idParser(_idParser)
    , m_roleFunctionParser(_roleFunctionParser)
    , m_descriptionParser(_descriptionParser)
    , m_publicKeyParser(_publicKeyParser)
    , m_authorityParser(_authorityParser)
{

}

bool RoleParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Role());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("id")))
    {
        data = reader->attributes().value(QStringLiteral("id"));
        if (!m_idParser->parse(reader, data))
            return false;
        m_result->id = m_idParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("id: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("roleFunction")))
    {
        data = reader->attributes().value(QStringLiteral("roleFunction"));
        if (!m_roleFunctionParser->parse(reader, data))
            return false;
        m_result->roleFunction = m_roleFunctionParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("roleFunction: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("description")))
    {
        data = reader->attributes().value(QStringLiteral("description"));
        if (!m_descriptionParser->parse(reader, data))
            return false;
        m_result->descriptionOptional = Optional<QString>(m_descriptionParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("publicKey")))
    {
        data = reader->attributes().value(QStringLiteral("publicKey"));
        if (!m_publicKeyParser->parse(reader, data))
            return false;
        m_result->publicKeyOptional = Optional<QString>(m_publicKeyParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("authority")))
    {
        data = reader->attributes().value(QStringLiteral("authority"));
        if (!m_authorityParser->parse(reader, data))
            return false;
        m_result->authorityOptional = Optional<QString>(m_authorityParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Role *RoleParser::result()
{
    return m_result.take();
}

}